﻿app.controller('CreateLessonController', function ($scope, $http, $rootScope, $compile, notificationFactory, $routeParams, lessonFactory, pictureFactory, wordFactory, systemObjectTagFactory, fileFactory) {
    init();
    function init() {
        $scope.severFile = mainFileAddress;
        $scope.roleByGroup = JSON.parse(localStorage.getItem("menu"));
        $scope.userName = $rootScope.userName;
        //count--------------
        notificationFactory.countAddFriend(localStorage.getItem("idkey")).success(function (data) {
            $scope.countAddFriend = data;
        });
        notificationFactory.countFromRoom(localStorage.getItem("idkey")).success(function (data) {
            $scope.countFromRoom = data;
        });
        notificationFactory.countNewMessage(localStorage.getItem("idkey")).success(function (data) {
            $scope.countNewMessage = data;
        });

        $scope.addLesson = false;
        $scope.updateLesson = false;
        createMenu();
        createWord();

        $scope.showWordItem = false;
        var lessonId = 0;
        $scope.lessonData = { Name: null, LessonNumber: null, UserId: localStorage.getItem("idkey"), LessonContent: "", DateTime: null };
        $scope.listWord = [];
        $scope.listImage = [];
        var i = 0;

        $scope.addItemListWord = function () {
            i++;
            var itemWord = { No: i, Id: null, WordName: "", Type: "", Meaning: "", Pronounce: "", LessonId: null };

            $scope.listWord.push(itemWord);
        };

        $scope.deleteItem = function (index, id) {
            $scope.listWord.splice(index, 1);
            if (id != undefined && id > 0) {
                wordFactory.deleteWordById(id).success(function () {
                });
            }
        };
        // load dữ liệu ban đầu
        if ($routeParams.lessonId != null) {
            $scope.title = "cập nhật bài học";
            $scope.updateLesson = true;
            $scope.addLesson = false;
            lessonFactory.getLessonDetail($routeParams.lessonId).success(function (data) {
                $scope.lessonData = data;
            });
            wordFactory.getWordByLesson($routeParams.lessonId).success(function (data) {
                for (i; i < data.length; i++) {
                    var itemWord = { No: i, Id: data[i].Id, WordName: data[i].WordName, Type: data[i].Type, Meaning: data[i].Meaning, Pronounce: data[i].Pronounce, LessonId: data[i].LessonId };
                    $scope.listWord.push(itemWord);
                }
            });
            pictureFactory.getPictureByLesson($routeParams.lessonId).success(function (data) {
                $scope.listImage = data;
                //var item = { Id: null, Name: '12', LessonId: $routeParams.lessonId, PictureUrl: "12.jpg" };
                //$scope.listImage.push(item);
                //item = { Id: null, Name: '123', LessonId: $routeParams.lessonId, PictureUrl: "123.jpg" };
                //$scope.listImage.push(item);
            });

            systemObjectTagFactory.getTagByLesson($routeParams.lessonId).success(function (data) {
                $scope.tags = data;
            });
            lessonId = $routeParams.lessonId;
        } else {
            $scope.updateLesson = false;
            $scope.addLesson = true;
            $scope.title = "thêm bài học";
        }


        // xử lý dữ liệu
        $scope.addLessonClick = function () {
            if (lessonId == 0) {
                lessonFactory.postLesson($scope.lessonData).success(function (data) {
                    lessonId = data;
                    // đăng từ vựng
                    for (var item = 0 ; item < $scope.listWord.length; item++) {
                        if ($scope.listWord[item].LessonId == null)
                            $scope.listWord[item].LessonId = lessonId;
                    }
                    wordFactory.postWord($scope.listWord);
                    $scope.errorStatus = false;
                    $scope.successStatus = true;

                    //đăng picture
                    var listPictureAdd = [];
                    for (var l = 0; l < $scope.listImage.length; l++) {
                        if ($scope.listImage[l].Id == null) {
                            listPictureAdd.push($scope.listImage[l]);
                        }
                    }
                    pictureFactory.postPicture(listPictureAdd).success(function (data) {
                        //console.log(data);
                    });
                    //cập nhật tag

                }).error(function () {
                    $scope.errorStatus = true;
                    $scope.successStatus = false;
                });
            }
        };
        $scope.updateLessonClick = function () {
            lessonFactory.putLesson($scope.lessonData).success(function () {
                //cập nhật từ vựng
                for (var item = 0 ; item < $scope.listWord.length; item++) {
                    if ($scope.listWord[item].LessonId == null)
                        $scope.listWord[item].LessonId = lessonId;
                }
                wordFactory.postWord($scope.listWord).success(function () {

                });

                //cập nhật picture
                var listPictureAdd = [];
                for (var l = 0; l < $scope.listImage.length; l++) {
                    if ($scope.listImage[l].Id == null) {
                        listPictureAdd.push($scope.listImage[l]);
                    }
                }
                pictureFactory.postPicture(listPictureAdd).success(function (data) {
                    //console.log(data);
                });
                //cập nhật tag
                var listStringTag = $("#tag-new").val().split(';');
                if (listStringTag.length > 0 && listStringTag[0] != "") {
                    var listSysTag = [];
                    var listTag = [];
                    for (var j = 0; j < listStringTag.length; j++) {
                        var sysTagItem = { TagId: 1, LessonId: $routeParams.lessonId, UserId: localStorage.getItem("idkey"), TagName: listStringTag[j] };
                        var tagItem = { Text: listStringTag[j] };
                        listSysTag.push(sysTagItem);
                        listTag.push(tagItem);
                    }

                    systemObjectTagFactory.addRangeTag(listTag).success(function () {
                        systemObjectTagFactory.addRangeSystemObjectTag(listSysTag).success(function () {
                            $scope.tags = listSysTag;
                        });
                    });
                }

                $scope.errorStatus = false;
                $scope.successStatus = true;
            }).error(function () {
                $scope.errorStatus = false;
                $scope.successStatus = true;
            });
        };
        $scope.deleteTag = function (id) {
            systemObjectTagFactory.delTag(id).success(function () {
                systemObjectTagFactory.getTagByLesson($routeParams.lessonId).success(function (data) {
                    $scope.tags = data;
                });
            });
        };



        //---list image-----------------------
        $scope.listImageAdd = [];
        //$scope.sendServer = function () {
        //    $http.post("http://192.168.1.102:1234/api/file/ProcessRequest", {
        //        Text: myData
        //    }).success(function () {
        //        alert('success');
        //    }).error(function () {
        //        alert('err');
        //    });
        //};
        $scope.selectPicture = function () {
            navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
                quality: 50,
                destinationType: destinationType.DATA_URL,
                sourceType: pictureSource.PHOTOLIBRARY
            });
        };
        $scope.delImage = function (pictureUrl) {
            for (var im = 0; im < $scope.listImage.length; im++) {
                if ($scope.listImage[im].PictureUrl == pictureUrl) {
                    if ($scope.listImage[im].Id > 0) {
                        var id = $scope.listImage[im].Id;
                        pictureFactory.delPicture(id).success(function () {
                            console.log(id);
                            $("#img_" + id).css('display', 'none');
                        });
                    } else {
                        $scope.listImage.splice(im, 1);
                        console.log($scope.listImage);
                    }
                }
            }
        };
       
    }
    function onFail(message) { }

    function onPhotoDataSuccess(imageData) {
        var idata = "data:image/jpeg;base64," + imageData;
        var i = 0;

        fileFactory.uploadFile({ Text: imageData, Path: "lesson" }).success(function (data) {
            var item = { Id: null, Name: data.Text, LessonId: $routeParams.lessonId, PictureUrl: data.Text }
            $scope.listImage.push(item);
        });
    }
});

function createWord() {

}